<?php

namespace app\admin\controller\wxapp;

use app\common\controller\Backend;
use think\addons\AddonException;
use think\addons\Service;
use think\Db;
use think\Cache;
use think\Config;
use think\Session;
use think\Request;
use think\Exception;
use app\common\model\ShopProduct;
use app\common\model\ShopOrder;
use app\common\model\Order;
use app\common\model\WechatApplet;

/**
 * 应用市场
 *
 * @icon fa fa-circle-o
 * @remark 可在线部署、配置、提交审核小程序模板。UCToo.com已上线小程序应用市场 ，开发者可以发布免费或付费小程序模板：<a href="https://www.uctoo.com" target="_blank">https://www.uctoo.com</a>
 */
class Appstore extends Backend
{

    protected $model = null;
    protected $searchFields = 'pro_name';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\ShopProduct();
       // $this->appletLimit = $this->getAppletid();
    }

    /**
     * 查看
     */
    public function index()
    {
        $wxapps = get_wxapps_list(4);  //TODO:后台可配置应用市场产品显示哪个应用下的商城产品
        foreach ($wxapps as $k => &$v)
        {
           // $config = get_addon_config($v['name']);
           // $v['config'] = $config ? 1 : 0;
        }
        $this->assignconfig(['addons' => $wxapps]);
        return $this->view->fetch();
    }

    /**
     * 配置
     */
    public function config($ids = NULL)
    {
        $name = $this->request->get("name");
        if (!$name)
        {
            $this->error(__('Parameter %s can not be empty', $ids ? 'id' : 'name'));
        }
        if (!is_dir(ADDON_PATH . $name))
        {
            $this->error(__('Directory not found'));
        }
        $info = get_addon_info($name);
        $config = get_addon_fullconfig($name);
        if (!$info)
            $this->error(__('No Results were found'));
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            if ($params)
            {
                foreach ($config as $k => &$v)
                {
                    if (isset($params[$v['name']]))
                    {
                        if ($v['type'] == 'array')
                        {
                            $fieldarr = $valuearr = [];
                            $field = $params[$v['name']]['field'];
                            $value = $params[$v['name']]['value'];

                            foreach ($field as $m => $n)
                            {
                                if ($n != '')
                                {
                                    $fieldarr[] = $field[$m];
                                    $valuearr[] = $value[$m];
                                }
                            }
                            $params[$v['name']] = array_combine($fieldarr, $valuearr);
                            $value = $params[$v['name']];
                        }
                        else
                        {
                            $value = is_array($params[$v['name']]) ? implode(',', $params[$v['name']]) : $params[$v['name']];
                        }

                        $v['value'] = $value;
                    }
                }
                try
                {
                    //更新配置文件
                    set_addon_fullconfig($name, $config);
                    $this->success();
                }
                catch (Exception $e)
                {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("addon", ['info' => $info, 'config' => $config]);
        return $this->view->fetch();
    }

    /**
     * 下单
     */
    public function buy()
    {
       // $model = new \app\common\model\WxappUserTemplate();
       // $productIds = $model->where('template_id', 1)->select();
        $status['buyer_appletid'] = $appletId = $this->getAppletid();   //TODO:当前操作的应用,增加判断是小程序类型帐号
        if(!$appletId){                     //TODO:未选择当前操作的应用，前端提示先选择一个小程序帐号。
            return ['code'=>-1];
        }
        $wechat_appstore_appid = config('site.wechat_appstore_appid');
        $appstore = WechatApplet::get(['appid' => $wechat_appstore_appid]);
        trace($wechat_appstore_appid,'downloaded$wechat_appstore_appid:');
        $status['mp_id'] = $appstore['appletid'];          //系统中的mp_id字段统一约定为WechatApplet表appletid字段
        $status['name'] = $this->request->post("name");
        $status['pro_id'] = $id = input("id");
        trace($id,'downloaded$id:');
        trace($status['name'],'downloaded$name:');
        $product = ShopProduct::get($id);                  //用户购买的商品

        $uid = $this->auth->id;
        $user = getUserByUid($uid);   //TODO:存在一个uid对应多个user的情况
        $status['openid'] = $user['openid'];  //此时只能获取到用户在pc端扫码登录的openid
        $status['user_id'] = $user['id'];
        $status['orig_price'] = $product['pro_price'];
        $status['payment_price'] = $product['pro_price'];
        $status['coupon_price'] = 0;
        $userinfo = $this->auth->getUserInfo();
        trace($userinfo,'downloaded$userinfo:');
        $shopOrderModel = new ShopOrder();
        trace($shopOrderModel,'downloaded$shopOrderModel:');
        $shopOrder = $shopOrderModel->where('buyer_appletid', $appletId)->where('pro_id', $id)->find();
        trace($shopOrder,'downloaded$shopOrder:');
        trace($status,'downloaded$status:');
        if($shopOrder){     //正在操作的微应用下已经有相同商品订单，不再重复下单

            return ['code'=>1];         //TODO:前端提示订单已生成，支付按钮变有效，立即支付
        }else{
            Db::transaction(function () use ($status, &$res){
                $orderNo = ShopOrder::generateOrderCode();
                $createTime = date('Y-m-d h:i:s', time());
                $data['mp_id'] = $status['mp_id'];
                $data['order_no'] = $orderNo;
                $data['pro_id'] = $status['pro_id'];
                $data['openid'] = $status['openid'];
                $data['user_id'] = $status['user_id'];
                $data['buyer_appletid'] = $status['buyer_appletid'];
                $data['contact'] = '';
                $data['order_name'] = $status['name'];
                $data['orig_price'] = $status['orig_price'];
                $data['payment_price'] = $status['payment_price'];
                $data['freight_price'] = 0;
                $data['coupon_price'] = $status['coupon_price'];
                $data['status'] = 0;
                //$status['coupon_price'] > 0 && $data['coupon_code'] = $this->code;

                $order = ShopOrder::create($data);
                $res = [
                    'status' => 0,
                    'order_id' => $order['id'],
                    'order_no' => $orderNo,
                    'create_time' => $createTime
                ];
            });
            return ['code'=>1];
        }
    }

    /**
     * 支付方式选择页
     */
    public function pay()
    {
        // $model = new \app\common\model\WxappUserTemplate();
        // $productIds = $model->where('template_id', 1)->select();
        $status['buyer_appletid'] = $appletId = $this->getAppletid();
        $wechat_appstore_appid = config('site.wechat_appstore_appid');
        $mpopen_wxpay_appid = config('site.mpopen_wxpay_appid');
        $appstore = WechatApplet::get(['appid' => $wechat_appstore_appid]);
        $wxpay_app = WechatApplet::get(['appid' => $mpopen_wxpay_appid]);
        trace($wxpay_app,'downloaded$wxpay_app:');
        $status['mp_id'] = $appstore['appletid'];          //系统中的mp_id字段统一约定为WechatApplet表appletid字段
        $status['pro_id'] = $id = input("id");
        $product = ShopProduct::get($id);                  //用户购买的商品
        $uid = $this->auth->id;
        $user = getUserByUid($uid);   //TODO:存在一个uid对应多个user的情况
        $status['openid'] = $user['openid'];  //此时只能获取到用户在pc端扫码登录的openid
        $status['user_id'] = $user['id'];
        $status['orig_price'] = $product['pro_price'];
        $status['payment_price'] = $product['pro_price'];
        $status['coupon_price'] = 0;
        $userinfo = $this->auth->getUserInfo();
        $shopOrderModel = new ShopOrder();
        trace($userinfo,'downloaded$userinfo:');
        $shopOrder = $shopOrderModel->where('buyer_appletid', $appletId)->where('pro_id', $id)->find();
        $ispaid = $shopOrder['payment_time'] ? false : true;   //订单是否已经支付过
        //正在支付的订单已经支付过，不再重复支付a
            $this->view->assign([
                'appstore'        => $appstore,
                'wxpay_app'       => $wxpay_app,
                'product'       => $product,
                'shopOrder' => $shopOrder,
                'userinfo' => $userinfo,               //admin表帐号信息
                'user' => $user,                       //user会员信息
                'account_balance' => 0,
                'ispaid' => $ispaid,
                'createorder' => url('/admin/wxapp/appstore/createorder',['mp_id'=>$wxpay_app['appletid'],'order_no'=>$shopOrder['order_no']],false,true),

            ]);

            return $this->view->fetch();  //TODO:前端提示订单已支付，支付按钮变无效
    }


    /**
     * 生成通用订单表数据，跳转到统一支付收银台
     */
    public function createorder()
    {
        // $model = new \app\common\model\WxappUserTemplate();
        // $productIds = $model->where('template_id', 1)->select();
        $status['buyer_appletid'] = $appletId = $this->getAppletid();
        $wechat_appstore_appid = config('site.wechat_appstore_appid');
        $mpopen_wxpay_appid = config('site.mpopen_wxpay_appid');
        $appstore = WechatApplet::get(['appid' => $wechat_appstore_appid]);
        $wxpay_app = WechatApplet::get(['appid' => $mpopen_wxpay_appid]);
        trace($wxpay_app,'downloaded$wxpay_app:');
        $status['mp_id'] = $appstore['appletid'];          //系统中的mp_id字段统一约定为WechatApplet表appletid字段
        $order_no = input("order_no");
        trace($order_no,'downloaded$order_no:');

        $uid = $this->auth->id;
        $user = getUserByUid($uid);   //TODO:存在一个uid对应多个user的情况
        $userinfo = $this->auth->getUserInfo();
        $shopOrderModel = new ShopOrder();
        trace($userinfo,'downloaded$userinfo:');
        $shopOrder = $shopOrderModel->where('buyer_appletid', $appletId)->where('order_no', $order_no)->find();
        $product = ShopProduct::get($shopOrder['pro_id']);                  //用户购买的商品
        $order = new Order();
        $order->mid =  $user['id'];
        $order->uid  =   $user['uid'];
        $order->mp_id  =   $wxpay_app['appletid'];   //数据归属的应用
        $order->order_type  =  'uid';
        $order->order_id = $user['id'].'_'.date("YmdHis");    //order表的order_id字段不能重复
        $order->order_status = 0;
        $order->order_total_price = $shopOrder['payment_price']*100;   //界面输入的单位是元，转换为分
        $order->order_express_price = 0;
        $order->buyer_openid = $user['openid'];
        $order->buyer_nick = $user['nickname'];
        $order->receiver_name = $user['username'];
        $order->receiver_province = $user['province'];
        $order->receiver_city = $user['city'];
        $order->receiver_zone = '';
        $order->receiver_address = $user['address'] ? $user['address'] : '' ;
        $order->receiver_mobile = $user['mobile'];
        $order->receiver_phone = '';
        $order->product_id = $product['id'];
        $order->product_name = $product['pro_name'];
        $order->product_price = $product['pro_price']*100;
        $order->product_sku = json_encode($product['pro_attr']);
        $order->product_count = 1;
        $order->product_img = $product['pro_image'];
        $order->delivery_id = $shopOrder['shipping_no'];
        $order->delivery_company = '';
        $order->coupon = '';
        $order->trans_id = '';
        $order->module = 'admin';
        $order->addon = 'appstore';         //在微信支付回调通知中根据此字段进行特殊处理 PayNotifyCallBack
        $order->model_class = '';
        $order->aim_id = $shopOrder['id'];
        $order->pay_url = '';
        trace($order,'downloaded$order:');
        $order->save();
        $oid = $order->order_id;             //获得新增订单的id
        $this->redirect('/mpopen/index/index',['mp_id'=>$wxpay_app['appletid'],'order_id'=>$oid]); //跳转到微信支付收银台
    }

    /**
     * 安装
     */
    public function install()
    {
        $name = $this->request->post("name");
        $force = (int) $this->request->post("force");
        if (!$name)
        {
            $this->error(__('Parameter %s can not be empty', 'name'));
        }
        try
        {
            $uid = $this->request->post("uid");
            $token = $this->request->post("token");
            $version = $this->request->post("version");
            $faversion = $this->request->post("faversion");
            $extend = [
                'uid'       => $uid,
                'token'     => $token,
                'version'   => $version,
                'faversion' => $faversion
            ];
            Service::install($name, $force, $extend);
            $info = get_addon_info($name);
            $info['config'] = get_addon_config($name) ? 1 : 0;
            $info['state'] = 1;
            $this->success(__('Install successful'), null, ['addon' => $info]);
        }
        catch (AddonException $e)
        {
            $this->result($e->getData(), $e->getCode(), $e->getMessage());
        }
        catch (Exception $e)
        {
            $this->error($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 卸载
     */
    public function uninstall()
    {
        $name = $this->request->post("name");
        $force = (int) $this->request->post("force");
        if (!$name)
        {
            $this->error(__('Parameter %s can not be empty', 'name'));
        }
        try
        {
            Service::uninstall($name, $force);
            $this->success(__('Uninstall successful'));
        }
        catch (AddonException $e)
        {
            $this->result($e->getData(), $e->getCode(), $e->getMessage());
        }
        catch (Exception $e)
        {
            $this->error($e->getMessage());
        }
    }

    /**
     * 禁用启用
     */
    public function state()
    {
        $name = $this->request->post("name");
        $action = $this->request->post("action");
        $force = (int) $this->request->post("force");
        if (!$name)
        {
            $this->error(__('Parameter %s can not be empty', 'name'));
        }
        try
        {
            $action = $action == 'enable' ? $action : 'disable';
            //调用启用、禁用的方法
            Service::$action($name, $force);
            Cache::rm('__menu__');
            $this->success(__('Operate successful'));
        }
        catch (AddonException $e)
        {
            $this->result($e->getData(), $e->getCode(), $e->getMessage());
        }
        catch (Exception $e)
        {
            $this->error($e->getMessage());
        }
    }

    /**
     * 本地上传
     */
    public function local()
    {
        Config::set('default_return_type', 'json');

        $file = $this->request->file('file');
        $addonTmpDir = RUNTIME_PATH . 'addons' . DS;
        if (!is_dir($addonTmpDir))
        {
            @mkdir($addonTmpDir, 0755, true);
        }
        $info = $file->rule('uniqid')->validate(['size' => 10240000, 'ext' => 'zip'])->move($addonTmpDir);
        if ($info)
        {
            $tmpName = substr($info->getFilename(), 0, stripos($info->getFilename(), '.'));
            $tmpAddonDir = ADDON_PATH . $tmpName . DS;
            $tmpFile = $addonTmpDir . $info->getSaveName();
            try
            {
                Service::unzip($tmpName);
                @unlink($tmpFile);
                $infoFile = $tmpAddonDir . 'info.ini';
                if (!is_file($infoFile))
                {
                    throw new Exception(__('Addon info file was not found'));
                }

                $config = Config::parse($infoFile, '', $tmpName);
                $name = isset($config['name']) ? $config['name'] : '';
                if (!$name)
                {
                    throw new Exception(__('Addon info file data incorrect'));
                }

                $newAddonDir = ADDON_PATH . $name . DS;
                if (is_dir($newAddonDir))
                {
                    throw new Exception(__('Addon already exists'));
                }

                //重命名插件文件夹
                rename($tmpAddonDir, $newAddonDir);
                try
                {
                    //默认禁用该插件
                    $info = get_addon_info($name);
                    if ($info['state'])
                    {
                        $info['state'] = 0;
                        set_addon_info($name, $info);
                    }

                    //执行插件的安装方法
                    $class = get_addon_class($name);
                    if (class_exists($class))
                    {
                        $addon = new $class();
                        $addon->install();
                    }

                    //导入SQL
                    Service::importsql($name);

                    $info['config'] = get_addon_config($name) ? 1 : 0;
                    $this->success(__('Offline installed tips'), null, ['addon' => $info]);
                }
                catch (Exception $e)
                {
                    @rmdirs($newAddonDir);
                    throw new Exception($e->getMessage());
                }
            }
            catch (Exception $e)
            {
                @unlink($tmpFile);
                @rmdirs($tmpAddonDir);
                $this->error($e->getMessage());
            }
        }
        else
        {
            // 上传失败获取错误信息
            $this->error($file->getError());
        }
    }

    /**
     * 更新插件
     */
    public function upgrade()
    {
        $name = $this->request->post("name");
        if (!$name)
        {
            $this->error(__('Parameter %s can not be empty', 'name'));
        }
        try
        {
            $uid = $this->request->post("uid");
            $token = $this->request->post("token");
            $version = $this->request->post("version");
            $faversion = $this->request->post("faversion");
            $extend = [
                'uid'       => $uid,
                'token'     => $token,
                'version'   => $version,
                'faversion' => $faversion
            ];
            //调用更新的方法
            Service::upgrade($name, $extend);
            Cache::rm('__menu__');
            $this->success(__('Operate successful'));
        }
        catch (AddonException $e)
        {
            $this->result($e->getData(), $e->getCode(), $e->getMessage());
        }
        catch (Exception $e)
        {
            $this->error($e->getMessage());
        }
    }

    /**
     * 刷新缓存
     */
    public function refresh()
    {
        try
        {
            Service::refresh();
            $this->success(__('Operate successful'));
        }
        catch (Exception $e)
        {
            $this->error($e->getMessage());
        }
    }

    /**
     * 已装插件
     */
    public function wxapps()
    {
        $offset = (int) $this->request->get("offset");
        $limit = (int) $this->request->get("limit");
        $search = $this->request->get("search");
        $search = htmlspecialchars(strip_tags($search));
        $wechat_appstore_appid = config('site.wechat_appstore_appid');
        $appstore = WechatApplet::get(['appid' => $wechat_appstore_appid]);
        $addons = get_wxapps_list($appstore['id']);  //TODO:后台可配置应用市场产品显示哪个应用下的商城产品
        trace($addons,'downloaded$addons:');
        $mpId = get_admin_appletid();
        $uid = $this->auth->id;
        $model = new \app\common\model\WxappUserTemplate();
        $productIds = $model->where('uid', $uid)->where('mp_id', $mpId)->column('product_id');
        trace($productIds,'downloaded$productIds:');
        trace($mpId,'downloaded$mpId:');
        $list = [];
        foreach ($addons as $k => $v)
        {
            if ($search && stripos($v['pro_name'], $search) === FALSE && stripos($v['pro_content'], $search) === FALSE)
                continue;

            $v['flag'] = '';
            $v['banner'] = '';
            $v['image'] = '';
            $v['donateimage'] = '';
            $v['demourl'] = '';
            $v['buy'] = in_array($v['id'],$productIds);         //当前帐号下的小程序是否购买过此模版
            //$v['url'] = addon_url($v['name']);
            $list[] = $v;
        }
        trace($list,'downloaded$list:');
        $total = count($list);
        if ($limit)
        {
            $list = array_slice($list, $offset, $limit);
        }
        $result = array("total" => $total, "rows" => $list);

        $callback = $this->request->get('callback') ? "jsonp" : "json";
        return $callback($result);
    }

}
